<template>
  <div class="comment">
    <div class="avatar-username">
      <el-avatar :size="30" :src="avatar" />
      <span class="name">{{ comment.username }}</span>
    </div>
    <div class="rate" v-if="props.type === '1'">
      <el-rate
        v-model="comment.rate"
        size="small"
        show-score
        disabled
        score-template="{value} points"
        allow-half
        text-color="#ff9900"
      />
    </div>
    <div class="content">{{ comment.content }}</div>
    <div class="day-liked">
      <span class="day">{{ dateFormat(comment.day) }}</span>
      <div class="liked-comment">
        <div class="post-likes">
          <button class="like-button" @click="toggleLike" :class="{ liked: isLiked }">
            <font-awesome-icon :icon="['far', 'heart']" v-if="!isLiked" />
            <font-awesome-icon :icon="['fas', 'heart']" v-else />
          </button>
          <span class="count">{{ likedCount }}</span>
        </div>
        <div class="post-comments" v-if="props.type === '0'">
          <el-icon
            size="18"
            style="color: #000; margin: -1px 6px 0 6px; cursor: pointer"
            @click="replyNewComment"
          >
            <ChatLineRound />
          </el-icon>
          <span class="count">{{ subComments.length }}</span>
        </div>

        <el-popconfirm title="确定要删除这条评论吗?" @confirm="deleteComments">
          <template #reference>
            <div class="post-delete" v-if="userId === comment.userId">
              <el-icon size="18" style="margin: -1px 6px 0 6px; cursor: pointer">
                <MoreFilled />
              </el-icon>
            </div>
          </template>
        </el-popconfirm>
      </div>
    </div>
    <div v-if="replyStatus" class="input-reply">
      <el-avatar :size="30" :src="avatar" />
      <el-input
        v-model="newComment"
        style="width: 240px"
        :placeholder="`回复${comment.username}的评论...`"
        maxlength="100"
        show-word-limit
        clearable
        @keyup.enter="PostNewComment"
      />
      <el-button
        type="primary"
        style="margin-right: 10px"
        :disabled="newComment.length === 0"
        @click="PostNewComment"
      >
        发布
      </el-button>
    </div>
    <div class="sub-comment">
      <SubComment
        v-for="item in subComments"
        :obj="item"
        @deleteReply="getOldSubComments"
      ></SubComment>
    </div>
    <el-divider></el-divider>
  </div>
</template>

<script setup>
import SubComment from './SubComment.vue'
import { getAvatar, getAvatarById } from '@/api/user'
import {
  deletePostComment,
  getSubComments,
  isUserLikeComment,
  replyComment,
  thumbsUpComment,
} from '@/api/forum'
import { deleteGoodComment } from '@/api/shop'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { defineEmits, defineProps, ref } from 'vue'
import { dateFormat } from '@/utils/strutils'
import { useUserStore } from '@/stores'
import { isUserLikeShopComment, thumbsUpShopComment } from '@/api/shop'
import { onMounted } from 'vue'
import { ElNotification } from 'element-plus'

const userStore = useUserStore()

const userId = userStore.getUser()

const props = defineProps({
  obj: Object,
  type: {
    type: String,
    default: '0',
  },
})

const emit = defineEmits(['deleteComment', 'updateCommentCount'])

const comment = props.obj

// 判断评论类型（0记录 1商城）
const type = props.type

// 回复框内容
const newComment = ref('')

// 发表评论用户的头像
const avatar = ref('')

// 获取当前用户的头像
const getCurrentAvatar = async () => {
  avatar.value = await getAvatarById(props.obj.userId)
}

// 回复评论状态
const replyStatus = ref(false)

// 回复评论
const replyNewComment = () => {
  if (replyStatus.value) {
    replyStatus.value = false
  } else {
    replyStatus.value = true
  }
}

// 获取所有回复评论
const subComments = ref([])

const getOldSubComments = async () => {
  if (type === '0') {
    const { data } = (await getSubComments(comment.id)).data
    subComments.value = data
  }
  emit('updateCommentCount')
}

// 发布评论
const PostNewComment = async () => {
  let res = null
  if (type === '0') {
    res = (
      await replyComment({
        content: newComment.value,
        replyId: comment.id,
      })
    ).data
  }
  if (res.success) {
    newComment.value = ''
    replyStatus.value = false
    await getOldSubComments()
  } else {
    ElNotification({
      title: '错误',
      message: '回复评论失败，请稍后重试',
      type: 'error',
    })
  }
}

// 喜欢数量
const likedCount = ref(comment.liked)

// 是否喜欢
const isLiked = ref()

// 判断当前用户是否喜欢
const isUserLike = async () => {
  if (type === '0') {
    const { data } = (await isUserLikeComment(comment.id)).data
    isLiked.value = data
  } else {
    const { data } = (await isUserLikeShopComment(comment.id)).data
    isLiked.value = data
  }
}

// 点赞
const toggleLike = async () => {
  if (type === '0') {
    const { data } = (await thumbsUpComment(comment.id)).data
    // 获取改记录总体点赞数量
    likedCount.value = data
  } else {
    const { data } = (await thumbsUpShopComment(comment.id)).data
    likedCount.value = data
  }
  isLiked.value = !isLiked.value
}

// 删除评论
const deleteComments = async () => {
  let res = null
  if (type === '0') {
    // 删除帖子评论
    res = (await deletePostComment(comment.id)).data
  } else {
    // 删除商品评论
    res = (await deleteGoodComment(comment.id)).data
  }
  if (res.success) {
    ElNotification({
      title: '删除成功',
      message: '删除评论失败',
      type: 'success',
    })
    emit('deleteComment')
  } else {
    ElNotification({
      title: '错误',
      message: '删除评论失败，请稍后重试',
      type: 'error',
    })
  }
}

onMounted(() => {
  getCurrentAvatar()
  getOldSubComments()
  isUserLike()
})
</script>

<style scoped less="scss">
.comment {
  width: 100%;
  min-height: 50px;
  margin-bottom: 30px;

  .avatar-username {
    display: flex;
    justify-content: start;
    align-items: center;
    gap: 5px;
  }

  .rate {
    margin-left: 25px;
  }

  .content {
    padding-left: 20px;
  }

  .day-liked {
    display: flex;
    justify-content: space-between;

    padding: 10px 10px 5px 10px;

    .day {
      color: grey;
    }

    .liked-comment {
      display: flex;
      gap: 10px;

      .post-likes,
      .post-comments,
      .post-delete {
        display: flex;
        align-items: center;
        justify-content: start;
      }

      .count {
        cursor: pointer;
      }

      .like-button {
        width: 28px;
        height: 22px;
        background: none;
        border: none;
        cursor: pointer;
        font-size: 1.2em;
        margin-right: 3px;
      }

      .liked {
        color: red !important;
      }
    }
  }

  .input-reply {
    display: flex;
    align-items: center;
    justify-content: start;
    gap: 5px;

    width: 100%;
    height: 50px;
    padding-left: 10px;
  }

  .sub-comment {
    padding: 3px 0 0 20px;
  }
}
</style>
